package com.study.mike.service.impl;

import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.extra.spring.SpringUtil;
import com.alibaba.excel.EasyExcel;
import com.study.mike.common.utils.EncryptUtils;
import com.study.mike.model.dto.BookImportPO;
import com.study.mike.model.dto.ImportBookInfoListener;
import com.study.mike.model.entity.Book;
import com.study.mike.service.BookService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.dao.DuplicateKeyException;

import java.math.BigDecimal;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.List;

/**
 * @author KangHui
 * @Date 2023/6/26 17:46
 */
@Slf4j
public class BookRunnable implements Runnable {
    private final BookService bookService;
    private final String filePath;

    public BookRunnable(String filePath) {
        this.filePath = filePath;
        this.bookService = SpringUtil.getBean(BookService.class);

    }

    @Override
    public void run() {
        this.importBook();
    }

    public void importBook() {
        ImportBookInfoListener importBookInfoListener = new ImportBookInfoListener();
        // easyExcel对象完成导入
        EasyExcel.read(filePath, BookImportPO.class, importBookInfoListener).sheet().doRead();
        List<BookImportPO> bookImportPOS = importBookInfoListener.getBookImportPOS();
        List<Book> books = new ArrayList<>(10);
        bookImportPOS.forEach(x -> {
            Book book = new Book();
            BeanUtils.copyProperties(x, book);
            if (StrUtil.isNotBlank(x.getBookTime())) {
                try {
                    book.setBookTime(new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").parse(x.getBookTime()));
                } catch (ParseException e) {
                    e.printStackTrace();
                }
            }
            // todo 这里直接用自己的转换 easyExcel底层不支持对自定义枚举的转换
            // book.setStatus(BookStatusEnum.getEnum(x.getStatus()));
            if (ObjectUtil.isNotNull(x.getBookPrice())) {
                book.setBookPrice(new BigDecimal(x.getBookPrice()));
            }
            book.setBookNo(EncryptUtils.aesEncrypt(x.getBookNo()));
            book.setBookAuthor(EncryptUtils.aesEncrypt(x.getBookAuthor()));
            books.add(book);
        });
        for (Book book : books) {
            try {
                bookService.save(book);
            } catch (DuplicateKeyException e) {
                log.info("数据编号已经存在，该条数据导入失败");
                continue;
            }
        }
    }
}
